/**
 * Created by Dalyn on 2017/5/8.
 */
import React from "react";
import {hashHistory} from 'react-router';
import Relay from "react-relay";
import {Table, Button, Icon, Popconfirm, message, Input} from 'antd';
import ReactKey from "../../../util/ReactKey";
import Util from "../../../util/Util";
import GetPlanDetailMutation from './mutation/GetPlanDetailMutation';
import GetProDigestMutation from "../productionLicense/mutation/GetProDigestMutation"
import SavePlanDetailMutation from "./mutation/SavePlanDetailMutation"
import "../css/fabricRaw.css";
import "../css/productionManagement_common.css";
import SelectMaterialModal from "./SelectMaterialModal";
import DemandQuantityModal from "./DemandQuantityModal";
import AddImgModal from "../productionLicense/licenseEdit/AddImgModal";

export default class FabricRawEdit extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            editable: true,
            value: '',
            proDigestModel: [],
            context: [{}, {}],
            proMaterialIds: [],
            dataSource: [],
            materialIndex: 0,
            demandQuantityIndex: 0,
            loading: true,
            pdId: this.props.location.state.pdId,
            /*删除项*/
            planIdsDel: [],
            /**/
            isSave: true
        };
        this.isEmpty = true;
        this.isSave = true;
        this.planIdsDel = [];
        this.planDetailModelList = null;
        this.messageFlag = true;
        this.ref_thisTimeCount = [];
    }

    componentWillMount() {
        this.proDigest();
        this.getPlanDetail()
    }

    /*表格上方信息*/
    proDigest(pageSize, pageNum) {
        Relay.Store.commitUpdate(
            new GetProDigestMutation({
                pdId: this.state.pdId,
            }),
            {
                onFailure: () => {
                    message.error("网络请求失败")
                },
                onSuccess: (response) => {
                    let errorCode = response.getProDigest.responseData.errorCode;
                    let value = response.getProDigest.responseData.value;
                    if (errorCode == '0') {
                        let proDigestModel = response.getProDigest.responseData.proDigestModel;
                        this.setState({
                            proDigestModel: proDigestModel,
                        });
                    } else if (errorCode == 500) {
                        message.error('服务器错误，请联系系统管理员')
                    }
                }
            }
        )
    }

    /*拉取表格数据*/
    getPlanDetail() {
        Relay.Store.commitUpdate(
            new GetPlanDetailMutation({
                pdId: this.state.pdId,
            }),
            {
                onFailure: () => {
                    message.error("网络请求失败");
                    this.setState({
                        loading: false
                    })
                },
                onSuccess: (response) => {
                    let errorCode = response.getPlanDetail.responseData.errorCode;
                    if (errorCode == 0) {
                        let planDetailModelList = response.getPlanDetail.responseData.planDetailModelList;
                        if (planDetailModelList.length <= 0) {
                            planDetailModelList.push({
                                pdId: this.state.pdId || null,
                                planId: null,
                                productName: null,
                                imgUrl: null,
                                specification: null,
                                colour: null,
                                prickle: null,
                                needCount: null,
                                thisTimeCount: null,
                                totalCount: null,
                                varianceCount: null,
                                ratio: null,
                                remark: null,
                            })
                        }
                        this.planDetailModelList = JSON.parse(JSON.stringify(planDetailModelList));
                        this.setState({
                            dataSource: planDetailModelList,
                            loading: false
                        })
                    } else if (errorCode == 500) {
                        message.error('服务器错误，请联系系统管理员')
                    }
                }

            }
        );
    }

    /*保存表格数据*/
    savePlanDetail() {
        let ref_thisTimeCount = this.ref_thisTimeCount;
        Relay.Store.commitUpdate(
            new SavePlanDetailMutation({
                pdId: this.state.pdId,
                planIds: this.planIdsDel.join(","),
                planDetailJSON: JSON.stringify(this.state.dataSource),
            }),
            {
                onFailure: () => {
                    message.error("网络请求失败");
                    this.isSave = true;
                    this.setState({
                        loading: false,
                        // isSave: true,
                    })
                },
                onSuccess: (response) => {
                    let errorCode = response.savePlanDetail.responseData.errorCode;
                    if (errorCode == 0) {
                        let planDetailModelList = response.savePlanDetail.responseData.planDetailModelList;
                        if (!planDetailModelList.length) {
                            planDetailModelList.push({
                                pdId: this.state.pdId || null,
                                planId: null,
                                productName: null,
                                imgUrl: null,
                                specification: null,
                                colour: null,
                                prickle: null,
                                needCount: null,
                                thisTimeCount: null,
                                totalCount: null,
                                varianceCount: null,
                                ratio: null,
                                remark: null,
                            })
                        }
                        /*清空待删除项的数组*/
                        this.planIdsDel = [];
                        this.planDetailModelList = JSON.parse(JSON.stringify(planDetailModelList));
                        this.setState({
                            dataSource: planDetailModelList,
                        }, message.success("保存成功"))
                        ref_thisTimeCount.map((v,i)=>{
                            if(v.value){
                                v.value = ""
                            }
                        })
                    } else if (errorCode == 500) {
                        message.error('服务器错误，请联系系统管理员')
                    }
                    this.setState({
                        loading: false,
                        // isSave: true,
                    });
                    this.isSave = true
                }
            }
        );
    }

    /*点击保存*/
    saveMateriaClick() {
        // console.log(this.ref_thisTimeCount);
        this.isEmpty = true;
        this.isSave = true;
        let newData = [];
        let dataSource = this.state.dataSource;
        let reg = /^\s*$/g;
        dataSource.map((v, i) => {
            if (v.productName == undefined || v.productName == null || v.productName == "" ||
                v.needCount == undefined || v.needCount == null || v.needCount == "" || reg.test(v.needCount)) {
                this.isEmpty = false;
                return
            } else if (v.productName && v.productName.length <= 0) {
                this.isEmpty = false;
                return
            }
        });
        if (this.isEmpty == false) {
            message.warning("物料名称和需求数不能为空");
            return
        }
        if (this.isEmpty && this.isSave) {
            /*防止快速点击*/
            this.isSave = false;
            this.savePlanDetail();
            /*  this.setState({
             isSave: false,
             }, this.savePlanDetail);*/
        }
        /*this.setState({
         // proMaterialIds: this.proMaterialIds
         },this.savePlanDetail);*/
    }

    /*删除行*/
    onDelete(index, planId) {
        /*dataSource dataSourceSelf分别代表两个数组，指针不同*/
        const dataSource = [...this.state.dataSource];
        const dataSourceSelf = [...this.planDetailModelList];
        dataSource.splice(index, 1);
        dataSourceSelf.splice(index, 1);
        if (planId) {
            this.planIdsDel.push(planId);
        }
        this.planDetailModelList = dataSourceSelf;
        this.setState({
            dataSource
        });
    }

    /*添加行*/
    handleAdd = () => {
        const {dataSource} = this.state;
        const dataSourceSelf = this.planDetailModelList;
        if (dataSource.length >= 100) {
            message.warning("最多添加100条");
            return;
        }
        const newData = {
            pdId: this.state.pdId || null,
            productName: null,
            imgUrl: null,
            specification: null,
            colour: null,
            prickle: null,
            needCount: null,
            thisTimeCount: null,
            totalCount: null,
            varianceCount: null,
            ratio: null,
            remark: null,
        };
        let newDataSelf = JSON.parse(JSON.stringify(newData));
        this.planDetailModelList = [...dataSourceSelf, newDataSelf];
        this.setState({
            dataSource: [...dataSource, newData],
        });
    }
    /*手动输入*/
    InputChange(contextname, index, e) {
        let ref_thisTimeCount = this.ref_thisTimeCount;
        let dataSource = this.state.dataSource;
        if (!dataSource[index]) {
            dataSource[index] = {}
        }
        let totalCount = Number(this.planDetailModelList[index].totalCount);
        let text = e.target.value;
        let reg1 = /^([0-9]{0,10})$/;
        let reg2 = /^([0-9]{0,10})+\.?[0-9]{0,2}$/;

        if (contextname == 'thisTimeCount') {
            let needCount = dataSource[index].needCount;
            if (!needCount) {
                if (this.messageFlag) {
                    this.messageFlag = false;
                    message.info("请先填写需求数");
                    clearTimeout(this.messageTime);
                    this.messageTime = setTimeout(() => {
                        this.messageFlag = true;
                    }, 1800);
                    return
                }
            }

            text = Number(text);
            if (!reg1.test(text)) {
                ref_thisTimeCount[index].value = null;
                return
            } else if (text.length > 10) {
                ref_thisTimeCount[index].value = e.target.value.toString(0, 10);
                return
            }
            /*累积到料计算*/
            dataSource[index].totalCount = totalCount + text;  // 转换
        }
        if (contextname == 'remark') {
            // let str_temp = text.replace(/[\u4e00-\u9fa5]/g, 'aa');//将汉字替换为aa
            if (text.length >= 50) {
                message.warning("最多可输入50个字符");
                // e.target.value = text.toString(0,50);
                // return
            }
        }
        // let context = dataSource[index];
        dataSource[index][contextname] = text;
        this.setState({
            dataSource: dataSource,
        },this.isSave = true);

    }

    /*物料名称数据*/
    selectMaterial(index, list) {
        let dataSourceSelf = this.state.dataSource;
        // let dataSourceSelf = dataSource.concat(list);

        dataSourceSelf[index].productName = list[0].productName;
        dataSourceSelf[index].specification = list[0].specification;
        dataSourceSelf[index].colour = list[0].colour;
        dataSourceSelf[index].prickle = list[0].prickle;
        dataSourceSelf[index].orderType = list[0].orderType;
        this.setState({
            dataSource: dataSourceSelf
        }, () => {
            this.refs.SelectMaterialModal.setState({
                SelectMaterialFlag: false,
            });
        });
    }

    /*物料点击*/
    materialClick(record, index) {
        this.setState({
            materialIndex: index,
        });
        // console.log(this.refs.SelectMaterialModal.rowSelection);
        // this.refs.SelectMaterialModal.rowSelection.selectedRowKeys = [];
        this.refs.SelectMaterialModal.setState({
            SelectMaterialFlag: true,
            loading: true,
        }, this.refs.SelectMaterialModal.getChildsGoods);
        /*this.refs.SelectMaterialModal.setState({
         SelectMaterialFlag:true,
         })*/
    }

    /*点击需求数量*/
    demandQuantityClick(record, index) {
        this.setState({
            demandQuantityIndex: index,
        });

        this.refs.DemandQuantityModal.setState({
            DemandQuantityFlag: true,
            // loading:true,
        }, this.refs.DemandQuantityModal.getPlanNeedCount(record.planId));
    }

    /*添加需求数-数据*/
    demandQuantity(index, num, data) {
        /*参数data是需求数表格数组*/
        let dataSourceSelf = this.state.dataSource;
        dataSourceSelf[index].needCount = num;
        data.pop();//删除data最后一条数据--求和
        dataSourceSelf[index].planNeedCountJSON = JSON.stringify(data);
        this.setState({
            dataSource: dataSourceSelf
        }, () => {
            this.refs.DemandQuantityModal.setState({
                DemandQuantityFlag: false,
                dataSource: [],
            });
        });
    }

    //显示上传图片弹框
    showimgmodal(index, imgURL) {
        // console.log(imgURL);
        this.refs.addimg.imgURL = imgURL;
        this.refs.addimg.setState({
            visible: true,
            index: index,
            imageUrl:imgURL
        });
    }

    //点击弹框确定之后url赋给src
    showImg(url, index) {
        let dataSource = this.state.dataSource;
        if (!dataSource[index]) {
            dataSource[index] = {}
        }
        // let context = dataSource[index];
        // context['imgUrl'] = url;
        dataSource[index].imgUrl = url;
        this.setState({
            dataSource: dataSource,
        });
        this.refs.addimg.setState({
            visible: false,
        });
    }

    render() {
        let {dataSource, proDigestModel} = this.state;
        const {value, editable} = this.state;
        const columns = [
            {
                title: '序号',
                dataIndex: 'index',
                key: 'index',
                width: 80,
                render: ((text, record, index) => {
                    return index + 1
                })
            },
            {
                title: <span><i className="prodution_fabricRaw_text_red">*</i>物料名称</span>,
                dataIndex: 'productName',
                key: 'productName',
                width: 260,
                onCellClick: (record, e, index) => {
                    /* this.setState({
                     materialPlanId:record.planId,
                     });
                     this.refs.SelectMaterialModal.setState({
                     SelectMaterialFlag:true,
                     })*/
                },
                render: (text, record, index) => {
                    let flag;
                    if (record.productName == null || record.productName == undefined || record.productName == "") {
                        flag = true
                    } else if (record.productName && record.productName.length >= 1) {
                        flag = false
                    } else {
                        flag = false
                    }
                    return flag ? (
                        <span className="prodution_fabricRaw_edit_span_edit_productName" ref={"productName"}
                              onClick={this.materialClick.bind(this, record, index)}
                              title={record.productName}>{record.productName}</span>
                    ) : (
                        <span className="prodution_fabricRaw_edit_span_edit_input" ref={"productName"}
                              onClick={this.materialClick.bind(this, record, index)}
                              title={record.productName}>{record.productName}</span>
                    )
                }
            },
            {
                title: '图片',
                dataIndex: 'imgUrl',
                key: 'imgUrl',
                width: 200,
                onCellClick: (record, e) => {
                    // console.log("图片");
                },
                render: ((text, record, index) => {
                    // return <span className="" ref={"imgUrl"}>{record.imgUrl}</span>
                    return <img width="94" height='32' style={{height: 32}}
                                className="prodution_fabricRaw_td_img_context" alt="+添加图片" src={record.imgUrl}
                                onClick={this.showimgmodal.bind(this, index, record.imgUrl)}/>
                })
            },
            {
                title: '规格',
                dataIndex: 'specification',
                key: 'specification',
                width: 100,
                render: (text, record, index) => {
                    return <span className="" ref={"specification"}>{record.specification}</span>
                }
            },
            {
                title: '颜色',
                dataIndex: 'colour',
                key: 'colour',
                width: 100,
                render: (text, record, index) => {
                    return <span className="" ref={"colour"}>{record.colour}</span>
                }

            },
            {
                title: '单位',
                key: 'prickle',
                dataIndex: 'prickle',
                width: 100,
                render: (text, record, index) => {
                    return <span className="" ref={"prickle"}>{record.prickle}</span>
                }
            },
            {
                title: <span><i className="prodution_fabricRaw_text_red">*</i>需求数</span>,
                dataIndex: 'needCount',
                key: 'needCount',
                width: 100,
                render: (text, record, index) => {
                    let flag;
                    if (record.needCount == null || record.needCount == undefined || record.needCount == "" || record.needCount == 0) {
                        flag = true
                    } else {
                        flag = false
                    }
                    return flag ? (
                        <span className="prodution_fabricRaw_edit_span_edit_needCount" ref={"needCount"}
                              onClick={this.demandQuantityClick.bind(this, record, index)}></span>
                    ) : (
                        <span className="prodution_fabricRaw_edit_span_edit_input" ref={"needCount"}
                              onClick={this.demandQuantityClick.bind(this, record, index)}>{record.needCount}</span>
                    )
                }
            },
            {
                title: "本次到料数",
                dataIndex: 'thisTimeCount',
                key: 'thisTimeCount',
                width: 100,
                render: (text, record, index) => {
                    return <input key={record.planId + index + "thisTimeCount"}
                                  className="prodution_fabricRaw_edit_input_edit"
                                  onChange={this.InputChange.bind(this, 'thisTimeCount', index)}
                                  type="text"  value={record.thisTimeCount}
                                  ref={(item)=>{this.ref_thisTimeCount[index] = item}}
                                  maxLength="10"
                    />
                }
            },
            {
                title: '累计到料数',
                dataIndex: 'totalCount',
                key: 'totalCount',
                width: 200,
                render: (text, record, index) => {
                    return <span className="" ref={"totalCount"}>{Math.round(Number(record.totalCount))}</span>
                }
            },
            {
                title: '差异数',
                dataIndex: 'varianceCount',
                key: 'varianceCount',
                width: 100,
                render: (text, record, index) => {

                    return <span className=""
                                 ref={"varianceCount"}>{Number(record.totalCount).toFixed(2) - Number(record.needCount)}</span>
                },
            },
            {
                title: '到料比例(%)',
                key: 'ratio',
                dataIndex: 'ratio',
                width: 100,
                render: (text, record, index) => {
                    const ratio = (record.totalCount && record.needCount) ? Number(record.totalCount / record.needCount) * 100 : 0;
                    return <span className="" ref={"ratio"}>{Math.round(ratio)}%</span>
                }
            },
            {
                title: '备注',
                dataIndex: 'remark',
                key: 'remark',
                width: 200,
                render: (text, record, index) => {
                    return (<input key={record.planId + index + "remark"}
                                   title={record.remark} rows={1} maxLength="50"
                                   className="prodution_fabricRaw_edit_input_edit"
                                   onChange={this.InputChange.bind(this, 'remark', index)}
                                   value={record.remark} type="text" ref={"remark"}
                    />)
                }
            },
            {
                title: '',
                dataIndex: '',
                key: '',
                width: 120,
                render: (text, record, index) => {
                    if (index == this.state.dataSource.length - 1) {
                        return (
                            <span>
                                <a className="order_from_sp_add" onClick={this.handleAdd.bind(this)}></a>&nbsp;
                                <a className="order_from_sp_minus"
                                   onClick={this.onDelete.bind(this, index, record.planId)}></a>
                            </span>
                        )
                        /*if (index != 0) {
                         return (
                         <span>
                         <a className="order_from_sp_add" onClick={this.handleAdd.bind(this)}></a>&nbsp;
                         <a className="order_from_sp_minus" onClick={this.onDelete.bind(this, index, record.planId)}></a>
                         </span>
                         )
                         } else {
                         return (<a className="order_from_sp_add" onClick={this.handleAdd}></a>)
                         }*/
                    } else {
                        return (
                            <a className="order_from_sp_minus"
                               onClick={this.onDelete.bind(this, index, record.planId)}></a>
                        )
                    }
                },
            }
        ];
        return (
            <div className="poduction_manage_box">
                <div className="prodution_fabricRaw_index_info">
                    <span className="productionLicense_index_p">
                        <span className="productionLicense_index_span">订单编号：</span>
                        <span className="productionLicense_index_orderspan">{proDigestModel.orderId}</span>
                    </span>
                    <span className="productionLicense_index_p">
                        <span className="productionLicense_index_span">客户：</span>
                        <span className="productionLicense_index_orderspan">{proDigestModel.customerName}</span>
                    </span>
                    <span className="productionLicense_index_p">
                        <span className="productionLicense_index_span">款号：</span>
                        <span className="productionLicense_index_orderspan">{proDigestModel.styleNo}</span>
                    </span>
                </div>
                <div>
                    <Table
                        columns={columns}
                        dataSource={dataSource}
                        bordered
                        className="order_table"
                        pagination={false}
                        style={{width: '100%', marginTop: "20px"}}
                        loading={this.state.loading}

                    />
                </div>
                <SelectMaterialModal
                    key={"SelectMaterial"}
                    ref={"SelectMaterialModal"}
                    _selectMaterial={this.selectMaterial.bind(this)}
                    _materialIndex={this.state.materialIndex}
                    orderId={proDigestModel.orderId}
                />
                <DemandQuantityModal
                    ref={"DemandQuantityModal"}
                    _demandQuantity={this.demandQuantity.bind(this)}
                    _demandQuantityIndex={this.state.demandQuantityIndex}
                />
                <AddImgModal ref={'addimg'} showImg={this.showImg.bind(this)} key={ReactKey.key}/>
                <div className="production_management_save">
                    <button className="production_management_saveBtn" onClick={this.saveMateriaClick.bind(this)}>保存</button>
                </div>

            </div>
        )
    }
}
